﻿using System;
using System.Collections.Generic;
using System.Linq;
using eAtlantida.Tools.Generator.Sql;

namespace eAtlantida.Tools.Operations
{
    public class ConnectOperation : Operation
    {
        public const string Name = "connect";

        public override void Execute(State state)
        {
            if (state.CommandParameters.Length == 0)
            {
                WriteMessage("Missing parameters! Type 'connect %connectionString%' for create connection.", MessageType.Warning);
                return;
            }

            var connectionString = string.Join(" ", state.CommandParameters);;
            WriteMessage("Connect with typing connection string...", MessageType.Default);
            var discover = new Discover(connectionString);
            List<string> tables;
            try
            {
                tables = discover.GetTables();
            }
            catch (ArgumentException)
            {
                WriteMessage("Connection string is writed incorrect. Please reconnect.", MessageType.Warning);
                return;
            }
            catch (Exception ex)
            {
                WriteMessage("Some errors: " + ex.Message, MessageType.Warning);
                return;
            }
            
            if (tables.Any())
            {
                state.ConnectionString = connectionString;
                WriteMessage("Was find next tables:" + string.Join(", ", tables), MessageType.Info);
            }
            else
            {
                WriteMessage("Not found any tables.", MessageType.Warning);
                WriteMessage("Please set another connection.", MessageType.Request);
            }
        }
    }
}